package com.tho.ccolor;

import com.buzzingandroid.ui.HSVColorPickerDialog;
import com.buzzingandroid.ui.HSVColorPickerDialog.OnColorSelectedListener;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;

public class ColorActivity extends Activity implements OnTouchListener{
	
	private static final String  TAG = "Color::Activity";
	private static final int SELECT_PICTURE = 1;
	private static final int SELECT_TOOL = 2;
	private static final CharSequence[] items = {"Lasso Tool","Change color tool"}; 
	private String imagePath;
	private Bitmap mBitmap;
	private Point mPoint;
	private ColorHSV mNewColor;
	private double mScalingFactor;
	private ColorChanger mColorChanger;
	
    ImageView mImageView;
    
    public ColorActivity() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }
	    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_color);
		//set default color
		//mNewColor = new Scalar(45,255,0);
		mImageView = (ImageView) findViewById(R.id.mainImageView);	
		mImageView.setOnTouchListener(this);
		mPoint = new Point(0, 0);
		mNewColor = new ColorHSV(1, 1, 0.5f);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.color, menu);
		return true;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int rows = mBitmap.getHeight();
		int cols = mBitmap.getWidth();
		
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			//Point p = new Point();

			mPoint.x = (int)(event.getX()/mScalingFactor);
			mPoint.y =  (int)(event.getY()/mScalingFactor);
			process();
		}
		return false;
	}

	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.action_browse:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	      break;
	    case R.id.action_settings:
	    	HSVColorPickerDialog cpd = new HSVColorPickerDialog( this, 0xFF4488CC, new OnColorSelectedListener() {
	    	    //@Override
	    	    public void colorSelected(Integer color) {
	    	        // Do something with the selected color
	    	    	if(color != null){
	    	    		float[] hsvColor = new float[3];
	    	    		
	    	    		Color.colorToHSV(color, hsvColor);	    	    		
	    	    		mNewColor = new ColorHSV(hsvColor[0], hsvColor[1], hsvColor[2]);
	    	    		Toast.makeText(ColorActivity.this, "hue:" + hsvColor[0] + ", satu:" + hsvColor[1], Toast.LENGTH_SHORT).show();
	    	    	}else{
	    	    		Toast.makeText(ColorActivity.this, "color is null", Toast.LENGTH_SHORT).show();
	    	    	}
	    	    }
	    	});
	    	cpd.setTitle( "Pick a color" );
	    	cpd.show();	    		      
	    	break;
	    case R.id.action_lasso:
//	    	selectTool();
//	    	Intent intentLasso = new Intent(this, LassoActivity.class);
	    	//startActivity(intentLasso);
	    	//intentLasso.setAction(action);
//	    	startActivityForResult(intentLasso, SELECT_TOOL);
	    	break;
	    default:	    	
	    	break;
	    }

	    return true;
	  }
	   
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                imagePath = getPath(selectedImageUri);
                //mImageView.setImageURI(selectedImageUri);
		
        		mBitmap = BitmapFactory.decodeFile(imagePath);        		
        				
        		//Mat img = Highgui.imread("/sdcard/Pictures/100075.jpg");
//        		img.inv();
        		mImageView.setImageBitmap(mBitmap);
        		//initialize ColorChanger tool
        		mColorChanger = new ColorChanger(mBitmap);
        		ViewTreeObserver vto = mImageView.getViewTreeObserver();
        		mImageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        		    public boolean onPreDraw() {
        		        mScalingFactor = mImageView.getMeasuredHeight()*1.0/mBitmap.getHeight();
        		        return true;
        		    }
        		});        		
        		//mScalingFactor = mImageView.getHeight()/mBitmap.getHeight();
            }else if (requestCode == SELECT_TOOL){
            	//mLasso = data.getBooleanExtra(LassoActivity.IS_LASSO, false);
            }
        }
    }
 
    private void process(){
		int rows = mBitmap.getHeight();
		int cols = mBitmap.getWidth();		
		
		if( mPoint.x < cols && mPoint.y < rows){
			//process here
			//int touchedColor = mBitmap.getPixel(mPoint.x, mPoint.y);
			//ColorHSV new
			mBitmap = mColorChanger.replaceColor(mPoint, mNewColor);
			mImageView.setImageBitmap(mBitmap);
		}
    	
    }
    private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }	
}
